const { execSQL } = require('../database/mysql');

//获取博客列表数据
const getBlogList=(author,keyword)=>{
    let sql=`select * from blogs where 1=1 `;
    if(author){
        sql+=`and author='${author}' `;
    }
    if(keyword){
        sql+=`and title like '%${keyword}%' `;
    }

    return execSQL(sql);
}

// 获取博客详情数据
const getBlogDetail=(id)=>{
    const sql=`select * from blogs where id='${id}'`;
    execSQL(sql).then((rows)=>{
        return rows[0];//rows时一个返回的对象数组，只有一个对象，所以通过返回row[0]就可以了
    })
}

//创建新的博客
const createNewBlog=(blogData)=>{
    const title=blogData.title;
    const content=blogData.content;
    const author=blogData.author;
    const createdAt=Date.now();

    const sql=`insert into blogs (title, content, author, createdAt) values('${title}', '${content}', '${author}', ${createdAt});`
    return execSQL(sql).then(insertedResult=>{
        console.log('insertedResult',insertedResult);
        return{
            id:insertedResult.insertId
        }
    })
}

//更新博客
const updateBlog=(id,blogData)=>{  
    const title=blogData.title;
    const content=blogData.content;
    const sql=`update blogs set title='${title}', content='${content}' where id=${id};`;
    return execSQL(sql).then(updateResult=>{
        console.log('updateResult',updateResult);
        if(updateResult.affectedRows>0){//该属性大于0的时候证明更新成功了
            return true;
        }
        return false;
    })
}

const deleteBlog=(id,author)=>{
    //实际开发中尽量使用update进行软删除
    const sql=`delete from blogs where id=${id} and author='${author}'`;
    return execSQL(sql).then(deleteResult=>{
        console.log('updateResult',deleteResult);
        if(deleteResult.affectedRows>0){//该属性大于0的时候证明更新成功了
            return true;
        }
        return false;
    })
}

module.exports={
    getBlogList,
    getBlogDetail,
    createNewBlog,
    updateBlog,
    deleteBlog
}